package com.panopset;

import java.io.IOException;

import com.panopset.io.StreamProcessor;

/**
 * Sometimes you have to spin off another JVM. This class will patiently wait up
 * to five seconds, then give you the results of any System.out's the spun off
 * process may call.
 *
 * @author Karl Dinwiddie
 *
 */
public final class ProcessManager {

    /**
     * 25.
     */
    private static final int DFT_TRIES = 25;

    /**
     * Sleep time is 200.
     */
    private static final int SLEEP_TIME = 200;

    /**
     * Checks for a result every 200 milliseconds, for five seconds (25 tries).
     *
     * @param cmd
     *            Command.
     * @return Results of System.out and System.err.
     */
    public static String getResult(final String cmd) {
        return getResult(cmd, DFT_TRIES);
    }

    /**
     * Use this method only if you want to wait for a time period other than a
     * maximum of five seconds.
     *
     * @param cmd
     *            Command.
     * @param tries
     *            Each try is 200 milliseconds.
     * @return Results of System.out and System.err.
     */
    public static String getResult(final String cmd, final int tries) {

        Process process;
        try {
            process = Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            Util.log(e);
            return e.getMessage();
        }

        int trs = 0;
        while (trs++ < tries) {
            try {
                if (process.exitValue() != 0) {
                    process.destroy();
                }
            } catch (IllegalThreadStateException ex) {
                try {
                    Thread.sleep(SLEEP_TIME);
                } catch (InterruptedException e) {
                    Util.log(e);
                }
            }
        }
        String err = StreamProcessor.getStream(process.getErrorStream());
        if (err != null && err.length() > 0) {
            return err;
        }
        return StreamProcessor.getStream(process.getInputStream());
    }

    /**
     * Prevent instantiation.
     */
    private ProcessManager() {
    }

}
